package com.derbysoft.lowcostadapter.utils;

import org.dom4j.Document;
import org.dom4j.io.DocumentSource;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;

import javax.xml.transform.Source;

public class XmlToObject {
    protected static Logger logger = LoggerFactory.getLogger(XmlToObject.class);
    protected static Jaxb2Marshaller marshaller = new Jaxb2Marshaller();

    static {
        marshaller.setContextPath("com.derbysoft.lowcostadapter.commons.dto");
        try {
            marshaller.afterPropertiesSet();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    public static Object readObject(String file, Jaxb2Marshaller marshaller) {
        try {
            SAXReader reader = new SAXReader();
            Document document = reader.read(XmlToObject.class.getResourceAsStream(file));
            Source source = new DocumentSource(document);
            return marshaller.unmarshal(source);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new IllegalStateException();
        }
    }

    public static Object readObject(String file) {
        return readObject(file, marshaller);
    }
}
